/**
 * Copyright (C), 2001-2023, www.bosssof.com.cn
 * FileName: UserServiceImpl
 * Author: Administrator
 * Date: 2023-03-31 11:41:55
 * Description:
 * <p>
 * History:
 * <author> Administrator
 * <time> 2023-03-31 11:41:55
 * <version> 1.0.0
 * <desc> 版本描述
 */
package com.bosssoft.quickstart.demo.service.impl;

import com.bosssoft.quickstart.demo.constant.GlobalConstant;
import com.bosssoft.quickstart.demo.dao.entity.User;
import com.bosssoft.quickstart.demo.dao.mapper.UserMapper;
import com.bosssoft.quickstart.demo.exception.BizErrorCode;
import com.bosssoft.quickstart.demo.exception.BusinessException;
import com.bosssoft.quickstart.demo.pojo.dto.IdVersion;
import com.bosssoft.quickstart.demo.pojo.dto.UserDTO;
import com.bosssoft.quickstart.demo.pojo.query.UserQuery;
import com.bosssoft.quickstart.demo.pojo.vo.CommonPage;
import com.bosssoft.quickstart.demo.service.UserService;
import com.bosssoft.quickstart.demo.utils.IdGenerator;
import com.bosssoft.quickstart.demo.utils.MyBeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import tk.mybatis.mapper.entity.Example;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
/**
 * @ClassName: UserServiceImpl
 * @Description: 类的主要功能描述
 * @Author: Administrator
 * @Date: 2023-03-31 11:41
 **/
@Slf4j
@Validated
@Service
public class UserServiceImpl implements UserService {
    /**
     *  用户姓名列
     */
    private static final String PROPERTY_NAME="name";
    /**
     * 用户身份证id列
     */
    private static final String PROPERTY_CITIZEN_ID="citizenId";
    /**
     *  查询的排序条件
     */
    private static final String QUERY_RESULT_SORT_CONDITION="updated_time DESC";
    /**
     * 处理用户表数据
     */
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IdGenerator idGenerator;
    @Override
    public Boolean add(@NotNull @Valid UserDTO userDTO) {
        // 业务规则校验身份证号不可重复
        if(null!=this.findUserByCitizenId(userDTO.getCitizenId(),null)){
            throw new BusinessException(BizErrorCode.DATA_SEARCH_FOUND_MANNY,"系统存在相同身份证号用户");
        }
        User user=new User();
        BeanUtils.copyProperties(userDTO,user);

        user.setId(idGenerator.snowflakeId());
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());

        user.setVersion(idGenerator.snowflakeId());
        user.setStatus(GlobalConstant.ROW_DATA_STATUS_ACTIVE);
        log.info("test dev-tools");
        return userMapper.insert(user)>0;
    }

    @Override
    public Boolean remove(@NotNull Long id) {
        return userMapper.deleteByPrimaryKey(id)>0;
    }

    @Override
    public Boolean remove(@NotNull Long id, @NotNull Long version) {
        Example example=new Example(User.class);
        example.createCriteria()
                .andEqualTo(GlobalConstant.TableCommonField.ID_COLULMN_NAME,id).andEqualTo(GlobalConstant.TableCommonField.VERSION_COLUMN_NAME,version);
        return userMapper.deleteByExample(example)>0;
    }

    @Override
    public Boolean remove(@NotEmpty IdVersion[] idVersions) {
        // 在事务中启用批量删除
        for(IdVersion idVersion : idVersions){
            Example example =new Example(User.class);
            example.createCriteria().andEqualTo(GlobalConstant.TableCommonField.ID_COLULMN_NAME,idVersion.getId())
                    .andEqualTo(GlobalConstant.TableCommonField.VERSION_COLUMN_NAME,idVersion.getVersion());
            if (userMapper.deleteByExample(example)<=0){
                throw new BusinessException(BizErrorCode.DATA_DELETE_NOT_FOUND,"当前行的id和版本没匹配到记录");
            }
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean update(@NotNull @Valid UserDTO userDTO) {
        if(null==userDTO.getId()){
            throw new BusinessException(BizErrorCode.PARAM_VALID_FIELD_REQUIRE,"id为主键列不可为空");
        }
        // 判断系统不存在相同身份证号的
        if (findUserByCitizenId(userDTO.getCitizenId(),userDTO.getId())!=null){
            throw new BusinessException(BizErrorCode.DATA_SEARCH_FOUND_MANNY,
                    "身份证号系统已经使用，请换一个");
        }
        User user=new User();
        BeanUtils.copyProperties(userDTO,user);
        user.setUpdatedTime(new Date());
        user.setUpdatedBy(GlobalConstant.DEFAULT_MODIFIOR_ID);
        // 更新版本id
        user.setVersion(idGenerator.snowflakeId());
        Example example=new Example(User.class);
        example.createCriteria()
                .andEqualTo("id",userDTO.getId()).andEqualTo("version",userDTO.getVersion());
        return userMapper.updateByExampleSelective(user,example)>0;
    }

    @Override
    public CommonPage<UserDTO> search(@NotNull @Valid UserQuery userQuery) {
        Example exampleUser=new  Example(User.class);
        Example.Criteria criteriaUser =exampleUser.createCriteria();
        // 前端的查询条件是 and 关系所以一下用andlike
        if(!StringUtils.isEmpty(userQuery.getName())){
            criteriaUser.andLike(PROPERTY_NAME,"%"+userQuery.getName().trim()+"%");
        }
        if(!StringUtils.isEmpty(userQuery.getCitizenId())){
            criteriaUser.andLike(PROPERTY_CITIZEN_ID,"%"+userQuery.getCitizenId().trim()+"%");
        }
        exampleUser.setOrderByClause(QUERY_RESULT_SORT_CONDITION);
        /**
         * 构建包含分页信息的列表
         */
        PageMethod.startPage(userQuery.getPageIndex(),userQuery.getPageSize());
        Page<User> userPage= (Page<User>) userMapper.selectByExample(exampleUser);
        List<UserDTO> userDTOList= MyBeanUtil.copyList(userPage,UserDTO::new,null);
        log.debug(String.format("pageNum=%d,pages=%d,total=%d,pageSize=%d ",userPage.getPageNum(),userPage.getPages(),
                userPage.getTotal(),userPage.getPageSize()));
        return new CommonPage(userPage.getTotal(),userPage.getPageNum(),userPage.getPageSize(),userPage.getPages(),userDTOList);
    }

    @Override
    public UserDTO findById(@NotNull Long id) {
        User user=userMapper.selectByPrimaryKey(id);
        return user==null ? new UserDTO() : MyBeanUtil.copyProperties(user,UserDTO::new);
    }

    /**
     *  返回特定身份证id的用户 有且只有一个多个的时候触发异常
     * @param citizenId 身份证id
     * @param exclusiveId 排除的主键id
     * @return 用户对象
     */
    private User findUserByCitizenId(String citizenId,Long exclusiveId ){
        if( StringUtils.isEmpty(citizenId)){
            throw new BusinessException(BizErrorCode.PARAM_VALID_FIELD_REQUIRE,"id不可以为空");
        }
        Example example=new Example(User.class);
        if(exclusiveId==null){
            example.createCriteria().andEqualTo(PROPERTY_CITIZEN_ID,citizenId);
        }else{
            // 排除当前记录
            example.createCriteria().andEqualTo(PROPERTY_CITIZEN_ID,citizenId)
                    .andNotEqualTo(GlobalConstant.TableCommonField.ID_COLULMN_NAME,exclusiveId);
        }


        return userMapper.selectOneByExample(example);
    }
}
